package lab.cloud.project.share;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.ProgressMonitor;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.SwingWorker;
import javax.swing.TransferHandler;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;



public class ClientView implements ChatObserver, FileObserver, LocalObserver{

	ClientModelInterface model;
	ClientControllerInterface controller;
	
	JFrame outFrame = null;
	JSplitPane vSplit = null;
	JSplitPane hSplit = null;
	JTree fileList = null;
	JTextField currentDir = null;
	JList filesInDir = null;
	JTextArea chatShow = null;
	JTextField chatInput = null;
	JPanel upper = null;
	JPanel lower = null;
	JPanel right = null;
	JTextArea description = null;
	JDialog upload = null;
	DefaultListModel filesInDirDataModel = new DefaultListModel();
	
	JDialog jd = null;
	JTextField jtf = null;
	JTextField remoteFileUrl = null;
	JTextArea jta = null;
    JProgressBar progressBar = null;
	JButton jbOk = null;
	JButton jbCancel = null;
	
	String fs = System.getProperties().getProperty("file.separator");
	
	public ClientView(ClientControllerInterface controller, ClientModelInterface model){
		this.model = model;
		this.controller = controller;
		model.registerChatObserver((ChatObserver) this);
		model.registerFileObserver((FileObserver) this);
		model.registerLocalObserver((LocalObserver) this);
	}
	
	public void createView(){
		vSplit = new JSplitPane();
		vSplit.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
		vSplit.setPreferredSize(new Dimension(1000,500));
		vSplit.setDividerSize(2);
		vSplit.setDividerLocation(700);
		
		hSplit = new JSplitPane();
		hSplit.setOneTouchExpandable(true);
		hSplit.setOrientation(JSplitPane.VERTICAL_SPLIT);
		hSplit.setPreferredSize(new Dimension(700,500));
		hSplit.setDividerSize(2);
		hSplit.setDividerLocation(200);
		
		upper = new JPanel();
		upper.setLayout(new BoxLayout(upper, BoxLayout.PAGE_AXIS));
		upper.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		lower = new JPanel();
		lower.setLayout(new BoxLayout(lower, BoxLayout.PAGE_AXIS));
		lower.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		
		currentDir = new JTextField(30);
		currentDir.addKeyListener(new KeyAdapter(){
                @Override
			public void keyPressed(KeyEvent e){
				char ck = e.getKeyChar();
				if (ck == '\n'){
					String p = currentDir.getText();
					model.setCurrentDir(p);
				}
			}
		});
		//currentDir.addKeyListener(new UrlChangeListener());
		upper.add(createPanelForComponent(currentDir, "Current Directory"));
		
		filesInDir = new JList();
		filesInDir.setVisibleRowCount(-1);
		filesInDir.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		filesInDir.setModel(filesInDirDataModel);	
		filesInDir.setLayoutOrientation(JList.HORIZONTAL_WRAP);
		filesInDir.addMouseListener(new DoubleClickDirectoryListener());
		filesInDir.setCellRenderer(new FileListCellRender());
		filesInDir.setTransferHandler(new FileDragHandler());
		filesInDir.setDragEnabled(true);
		JScrollPane listView = new JScrollPane(filesInDir);
		listView.setPreferredSize(new Dimension(700, 170));
		upper.add(createPanelForComponent(listView, "Files List"));
		updateLocal();
		
		chatShow = new JTextArea();
		chatShow.setEditable(false);
		chatShow.setLineWrap(true);
		JScrollPane chatShowScroll = new JScrollPane(chatShow);
		chatShowScroll.setPreferredSize(new Dimension(700, 270));
		lower.add(createPanelForComponent(chatShowScroll, "Chatting"));
		
		chatInput = new JTextField(30);
		chatInput.setEditable(true);
		chatInput.addKeyListener(new ChatInputChangeListener());
		lower.add(createPanelForComponent(chatInput,"Say something here..."));
		
		DefaultMutableTreeNode allFiles = new DefaultMutableTreeNode("All Files");
		DefaultMutableTreeNode update = new DefaultMutableTreeNode("Update");
		DefaultMutableTreeNode today = new DefaultMutableTreeNode("Today");
		DefaultMutableTreeNode week = new DefaultMutableTreeNode("Last Week");
		DefaultMutableTreeNode month = new DefaultMutableTreeNode("Last Month");
		DefaultMutableTreeNode all = new DefaultMutableTreeNode("All");
		DefaultTreeModel treeModel = new DefaultTreeModel(allFiles);
		fileList = new JTree(treeModel);
		fileList.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		allFiles.add(update);
		allFiles.add(today);
		allFiles.add(week);
		allFiles.add(month);
		allFiles.add(all);
		
		fileList.setDragEnabled(true);
		fileList.setLargeModel(true);
		fileList.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		//fileList.addTreeSelectionListener(new FileTreeSelectionListener());
		fileList.addMouseListener(new ClickTreeItem());
		fileList.addMouseListener(new DoubleClickTreeItem());
		//fileList.addTreeExpansionListener(new FileTreeExpansionListener());
		fileList.setTransferHandler(new FileTreeTransferHandler());
		fileList.setDropMode(DropMode.ON);
		
		JScrollPane treeView = new JScrollPane(fileList);
		treeView.setPreferredSize(new Dimension(300,300));
		right = new JPanel();
		right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));
		right.setBounds(5, 5, 5, 5);
		right.add(createPanelForComponent(treeView, "Shared File List"));
		
		description = new JTextArea();
		description.setEditable(false);
		description.setLineWrap(true);
		description.setPreferredSize(new Dimension(300, 200));
		JScrollPane desScroll = new JScrollPane(description);
		right.add(createPanelForComponent(desScroll, "Selected Description"));
		updateFile();
		
		vSplit.setLeftComponent(hSplit);
		vSplit.setRightComponent(right);
		
		hSplit.setTopComponent(upper);
		hSplit.setBottomComponent(lower);
		
		outFrame = new JFrame("Client Window");
        //outFrame.setBackground(Color.GRAY);
		outFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
		outFrame.setBounds((d.width - 1000)/2 , (d.height - 500)/2, 1000, 500);
		outFrame.addWindowListener(new ClientWindowCreatedFocus());
		outFrame.getContentPane().add(vSplit, BorderLayout.CENTER);
		outFrame.pack();
		outFrame.setResizable(false);
		outFrame.setVisible(true);
	}
	
    public void createDownloadDialog(String localFile, String remoteFile){
        jd = new JDialog();
        jd.setModal(true);
        jd.setLocationRelativeTo(outFrame);
        jd.setTitle("Download Selected Files");
        jd.setSize(320, 250);
        jd.setLayout(new BorderLayout());

        JPanel all = new JPanel();
        all.setLayout(new BoxLayout(all, BoxLayout.PAGE_AXIS));
        all.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        remoteFileUrl = new JTextField(30);
		remoteFileUrl.setSize(300, 30);
		remoteFileUrl.setText(remoteFile);
		remoteFileUrl.setEditable(false);
		remoteFileUrl.setEnabled(false);
		all.add(createPanelForComponent(remoteFileUrl, "Remote File Path"));
        
        jtf = new JTextField(30);
		jtf.setSize(300, 30);
		jtf.setText(localFile);
		jtf.setEditable(false);
		jtf.setEnabled(false);
		all.add(createPanelForComponent(jtf, "Local File Path"));

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        all.add(createPanelForComponent(progressBar, "Download Progress..."));

        JPanel bp = new JPanel();
		bp.setLayout(new FlowLayout());
		jbOk = new JButton("Download");
		jbCancel = new JButton("Close");
		ActionListener buttonAction = new FileDownloadButtonListener();
		jbOk.addActionListener(buttonAction);
		jbCancel.addActionListener(buttonAction);
		bp.add(jbOk);
		bp.add(jbCancel);
		all.add(bp);

		jd.setLocationRelativeTo(null);
		jd.getContentPane().add(all, BorderLayout.CENTER);
		jd.setResizable(false);
		jd.setVisible(true);

    }
	public void createUploadDialog(String localFile, String remoteFile){
		jd = new JDialog();
        jd.setModal(true);
		jd.setLocationRelativeTo(outFrame);
		jd.setTitle("Upload Files & Descriptions...");
		jd.setSize(320, 450);
		jd.setLayout(new BorderLayout());
		
		JPanel all = new JPanel();
		all.setLayout(new BoxLayout(all, BoxLayout.PAGE_AXIS));
		all.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		
		jtf = new JTextField(30);
		jtf.setSize(300, 30);
		jtf.setText(localFile);
		jtf.setEditable(false);
		jtf.setEnabled(false);
		all.add(createPanelForComponent(jtf, "Local File Path"));
		
		remoteFileUrl = new JTextField(30);
		remoteFileUrl.setSize(300, 30);
		remoteFileUrl.setText(remoteFile);
		remoteFileUrl.setEditable(false);
		remoteFileUrl.setEnabled(false);
		all.add(createPanelForComponent(remoteFileUrl, "Remote File Path"));
		
		jta = new JTextArea();
		jta.setLineWrap(true);
		JScrollPane textScroll = new JScrollPane(jta);
		textScroll.setPreferredSize(new Dimension(300, 400));
		all.add(createPanelForComponent(textScroll, "Input Description for this file"));

		progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(true);
        all.add(createPanelForComponent(progressBar, "Upload Progress..."));
        
		JPanel bp = new JPanel();
		bp.setLayout(new FlowLayout());
		jbOk = new JButton("OK");
		jbCancel = new JButton("Close");
		ActionListener buttonAction = new FileUploadButtonListener(localFile);
		jbOk.addActionListener(buttonAction);
		jbCancel.addActionListener(buttonAction);
		bp.add(jbOk);
		bp.add(jbCancel);
		all.add(bp);
		
		jd.setLocationRelativeTo(null);
		jd.getContentPane().add(all, BorderLayout.CENTER);
		jd.setResizable(false);
		jd.setVisible(true);
	}
	@Override
	public void updateChat() {
		String showText = model.getChatShowText();
		chatShow.setText(showText);
	}

	@Override
	public void updateFile() {
		ArrayList fileData = model.getFileInfos();
		ArrayList<String> oldFileData = new ArrayList<String>();
		ArrayList<String> updateFile = new ArrayList<String>();
		
		model.parseFileByTime();
		DefaultMutableTreeNode root = (DefaultMutableTreeNode) fileList.getModel().getRoot();
		
		//Trave this Tree to construct oldFileData array
		Enumeration e = root.breadthFirstEnumeration();
		while (e.hasMoreElements()){
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
			if (node.getChildCount() == 0){
				oldFileData.add((String)node.getUserObject());
			}
		}
		//get the difference
		boolean flag;
		for (int i = 0; i < fileData.size(); i++){
			flag = true;
			FileInfo cur = (FileInfo) fileData.get(i);
			String curFile = cur.getFileName();
			for (String comp:oldFileData){
				if (curFile.equals(comp)){
					flag = false;
					break;
				}
			}
			if (flag){
				updateFile.add(curFile);
			}
		}
		
		DefaultMutableTreeNode update = (DefaultMutableTreeNode) root.getChildAt(0);
		update.removeAllChildren();
		for (String u:updateFile){
			DefaultMutableTreeNode n = new DefaultMutableTreeNode(u);
			update.add(n);
		}
		DefaultMutableTreeNode today = (DefaultMutableTreeNode) root.getChildAt(1);
		today.removeAllChildren();
		ArrayList<String> todays = new ArrayList<String>();
		for (int i = 0; i < model.getTodayFiles().size(); i++){
			FileInfo c = (FileInfo) model.getTodayFiles().get(i);
			todays.add(c.getFileName());
		}
		for (String u:todays){
			DefaultMutableTreeNode n = new DefaultMutableTreeNode(u);
			today.add(n);
		}
		DefaultMutableTreeNode week = (DefaultMutableTreeNode) root.getChildAt(2);
		week.removeAllChildren();
		ArrayList<String> weeks = new ArrayList<String>();
		for (int i = 0; i < model.getTodayFiles().size(); i++){
			FileInfo c = (FileInfo) model.getTodayFiles().get(i);
			weeks.add(c.getFileName());
		}
		for (String u:weeks){
			DefaultMutableTreeNode n = new DefaultMutableTreeNode(u);
			week.add(n);
		}
		DefaultMutableTreeNode month = (DefaultMutableTreeNode) root.getChildAt(3);
		month.removeAllChildren();
		ArrayList<String> months = new ArrayList<String>();
		for (int i = 0; i < model.getTodayFiles().size(); i++){
			FileInfo c = (FileInfo) model.getTodayFiles().get(i);
			months.add(c.getFileName());
		}
		for (String u:months){
			DefaultMutableTreeNode n = new DefaultMutableTreeNode(u);
			month.add(n);
		}
		DefaultMutableTreeNode allNode = (DefaultMutableTreeNode) root.getChildAt(4);
		allNode.removeAllChildren();
		ArrayList<String> allFiles = new ArrayList<String>();
		for (int i = 0; i < model.getFileInfos().size(); i++){
			FileInfo c = (FileInfo) model.getFileInfos().get(i);
			allFiles.add(c.getFileName());
		}
		for (String u:allFiles){
			DefaultMutableTreeNode n = new DefaultMutableTreeNode(u);
			allNode.add(n);
		}
		fileList.updateUI();
	}

	@Override
	public void updateLocal() {
		filesInDirDataModel.removeAllElements();
		filesInDirDataModel.addElement(".");
		filesInDirDataModel.addElement("..");
		File dir = new File(model.getCurrentDir());
		String[] files = dir.list();
		for (String file:files){
			File tmp = new File(file);
			if (!tmp.isHidden())
				filesInDirDataModel.addElement(file);
		}
		filesInDir.updateUI();
		currentDir.setText(model.getCurrentDir());
	}
	
	private JPanel createPanelForComponent(JComponent c, String title){
		JPanel panel = new JPanel(new BorderLayout());
		panel.add(c, BorderLayout.CENTER);
		if (title != null){
			panel.setBorder(BorderFactory.createTitledBorder(title));
		}
		return panel;
	}
	public void removeFileTreeReadItem(String fileName){
		DefaultMutableTreeNode root = (DefaultMutableTreeNode) fileList.getModel().getRoot();
		DefaultMutableTreeNode update = (DefaultMutableTreeNode) root.getChildAt(0);
		if (update.getChildCount() >= 1){
			DefaultMutableTreeNode c = null;
			for (c = (DefaultMutableTreeNode) update.getFirstChild(); c != null; c = c.getNextNode() ){
				if (fileName.equals((String) c.getUserObject())){
					//System.out.println((String)c.getUserObject());
					update.remove(c);
					break;
				}
			}
		}
		fileList.updateUI();
	}
	
	class ChatInputChangeListener extends KeyAdapter{
        @Override
		public void keyPressed(KeyEvent e){
			char ck = e.getKeyChar();
			if (ck == '\n'){
				String input = chatInput.getText();
				//model.setChatShowText(input);
				chatInput.setText(null);
				controller.sendChat(input);
			}
		}
	}
	class DoubleClickDirectoryListener extends MouseAdapter{
        @Override
		public void mouseClicked(MouseEvent e){
			if (e.getClickCount() == 2){
				String p = currentDir.getText();
				JList jl = filesInDir;
				int index = jl.getSelectedIndex();
				String selected = (String)jl.getModel().getElementAt(index);
				String filePath = null;
				if (".".equals(selected)){
					filePath = p;
				}else if ("..".equals(selected)){
					File path = new File(p);
					if (fs.equals(path.toString()))
						filePath = fs;
					else
						filePath = path.getParent();
				} else {
					filePath = p + fs + selected;
				}
				File selectedFile = new File(filePath);
				if (!selectedFile.isDirectory()){
					return;
				}
				model.setCurrentDir(filePath);		
			}
		}
	}
	class DoubleClickTreeItem extends MouseAdapter{
        @Override
		public void mouseClicked(MouseEvent e){
			TreePath tp  = null;
			if (e.getClickCount() == 2){
				tp = fileList.getPathForLocation(e.getX(), e.getY());
				if (tp == null) 
					return;
				DefaultMutableTreeNode clickNode = (DefaultMutableTreeNode) tp.getLastPathComponent();
				DefaultMutableTreeNode parent = (DefaultMutableTreeNode) clickNode.getParent();
				if (clickNode.getChildCount() == 0){
					String name = (String) clickNode.getUserObject();
					String localPath = model.getCurrentDir();
					String fullFileName = localPath + fs + name;
					//Download from Ftp
					FileInfo d = model.getFileInfo(name);
                    if (d == null)
                        return;
                    createDownloadDialog(fullFileName, d.getRemotePath());
					if ("Update".equals((String)parent.getUserObject()))
						removeFileTreeReadItem(name);
					description.setText("Download file to " + fullFileName);
				}
			}
		}
	}
	class ClickTreeItem extends MouseAdapter{
        @Override
		public void mouseClicked(MouseEvent e){
			TreePath tp = null;
			if (e.getClickCount() == 1){
				tp = fileList.getPathForLocation(e.getX(), e.getY());
				if (tp == null)
					return;
				try{
					DefaultMutableTreeNode clickNode = (DefaultMutableTreeNode) tp.getLastPathComponent();
					
					if (clickNode.getChildCount() == 0){
						String name = (String) clickNode.getUserObject();
						String path = model.getCurrentDir();
						String fullFileName = path + fs + name;
						String des = model.getFileInfo(name).getDescription();
						description.setText(fullFileName + "\n\n" + des);
					}
				}catch (NullPointerException err){}
			}
		}
	}
	class FileListCellRender extends JPanel implements ListCellRenderer{
		
		String text;
		Color background;
		Color foreground;
		
		@Override
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			text = (String) value;
			background = isSelected?list.getSelectionBackground():list.getBackground();
			String filePath = currentDir.getText() + fs + (String)list.getModel().getElementAt(index);
			foreground = isSelected?list.getSelectionForeground():list.getForeground();
			File file = new File(filePath);
			if (file.isDirectory()){
				foreground = new Color(10, 200, 10);
			}
			return this;
		}
        @Override
		public void paintComponent(Graphics g){
			g.setColor(background);
			g.fillRect(0, 0, getWidth(), getHeight());
			g.setColor(foreground);
			g.drawString(text, 5, 15);
		}
		public Dimension getPreferredSize(){
			return new Dimension(300, 20);
		}
	}
	class FileDragHandler extends TransferHandler{

		private static final long serialVersionUID = 1L;
		public Transferable createTransferable(JComponent jc){
			JList jl = (JList) jc;
			int index = jl.getSelectedIndex();
			String p = (String) jl.getModel().getElementAt(index);
			return new StringSelection(p);
		}
		public int getSourceActions(JComponent c){
			return COPY;
		}
	}
	class TreeCellRenderer extends DefaultTreeCellRenderer{
		private static final long serialVersionUID = 1L;

		public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, 
				boolean leaf, int row, boolean hasFocus){
			super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
			
			return tree;
			
		}
	}
	class Worker extends SwingWorker<Void, Void>{

		@Override
		protected Void doInBackground() throws Exception {
			int progress = 0;
			while (progress <= 100 && !isCancelled()){
				progress += 1;
				setProgress(progress);
				try{
					Thread.sleep(50);
				}catch(InterruptedException e){
					
				}
			}
			return null;
		}
	}
	class ProgressMonitorFileUpload implements PropertyChangeListener{
		String uploadFileName;
		ProgressMonitor pm;
		Worker worker;
		public ProgressMonitorFileUpload(String name){
			uploadFileName = name;
			pm = new ProgressMonitor(null, "���������ļ�: "+uploadFileName, " ", 0, 100);
			pm.setMillisToDecideToPopup(0);
			pm.setMillisToPopup(0);
			worker = new Worker();
			worker.addPropertyChangeListener(this);
			worker.execute();
		}
		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			if ("progress".equals(evt.getPropertyName())){
				int progress = (Integer) evt.getNewValue();
				pm.setProgress(progress);
				String message = String.format("�����: %d%%", progress);
				pm.setNote(message);
			}	
		}
	}
	class FileTreeTransferHandler extends TransferHandler{
		public boolean canImport(TransferHandler.TransferSupport info){
			if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)){
				return false;
			}
			return true;
		}
		public boolean importData(TransferHandler.TransferSupport info){
			if (!info.isDrop()){
				return false;
			}
			try {
				String fileName = (String)info.getTransferable().getTransferData(DataFlavor.stringFlavor);
				String remoteName = "research/share/" + fileName;
				fileName = currentDir.getText() + fs + fileName;
				createUploadDialog(fileName, remoteName);
				//upload = showFileInputDialog(fileName, fullFileName);
				//model.addFileInfo(n);
				//insertNewTreeItem(fileName);
				//fileList.updateUI();
			} catch (UnsupportedFlavorException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		}
		public int getSourceActions(JComponent c){
			return COPY;
		}
	}
	class ClientWindowCreatedFocus extends WindowAdapter{
		public void windowActivated(WindowEvent e){
			chatInput.requestFocus();
		}
	}
	class FileUploadButtonListener implements ActionListener{
		String fileUploadName = null;
		public FileUploadButtonListener(String name){
			fileUploadName = name;
		}
		@Override
		public void actionPerformed(ActionEvent e) {
			String buttonName = e.getActionCommand();
			if ("OK".equals(buttonName)){
				String localPath = jtf.getText();
				String remotePath = remoteFileUrl.getText();
				String[] dirs = localPath.split(fs);
				String fileName = dirs[dirs.length - 1];
                
                FtpStore ftpTask = new FtpStore("219.219.218.49", 21, true);
                ftpTask.setOkButton(jbOk);
                ftpTask.setCloseButton(jbCancel);
                ftpTask.setDescription(jta);
                ftpTask.setDialog(jd);
                
                ftpTask.setLocal(localPath);
                ftpTask.setRemote(remotePath);
                ftpTask.addPropertyChangeListener(new FileUploadProgressListener());
				ftpTask.execute();
                
				FileInfo n = new FileInfo();
				n.setAuthorName(model.getAuthor());
				n.setDescription(jta.getText());
				n.setFileDate(new Date());
				n.setFileName(fileName);
				n.setRemotePath(remoteFileUrl.getText());
				model.addFileInfo(n);
			}
			if ("Close".equals(buttonName)){
				jd.dispose();
			}
		}
        
	}
    class FileDownloadButtonListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			String buttonName = e.getActionCommand();
			if ("Download".equals(buttonName)){
				String localPath = jtf.getText();
				String remotePath = remoteFileUrl.getText();
				String[] dirs = localPath.split(fs);
				String fileName = dirs[dirs.length - 1];

                FtpStore ftpTask = new FtpStore("219.219.218.49", 21, false);
                ftpTask.setOkButton(jbOk);
                ftpTask.setCloseButton(jbCancel);
                ftpTask.setDescription(jta);
                ftpTask.setDialog(jd);

                ftpTask.setLocal(localPath);
                ftpTask.setRemote(remotePath);
                ftpTask.addPropertyChangeListener(new FileDownloadProgressListener());
				ftpTask.execute();
			}
			if ("Close".equals(buttonName)){
				jd.dispose();
			}
		}
    }
    class FileDownloadProgressListener implements PropertyChangeListener{
        @Override
        public void propertyChange(PropertyChangeEvent evt){
            if ("progress" == evt.getPropertyName()){
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
            }
        }
    }
    class FileUploadProgressListener implements PropertyChangeListener{
        @Override
        public void propertyChange(PropertyChangeEvent evt){
            if ("progress" == evt.getPropertyName()){ 
                int progress = (Integer) evt.getNewValue();
                progressBar.setValue(progress);
            }
        }
    }
   
}
